package com.aoeai.rg.language.data.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.aoeai.rg.language.data.model.Language
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.Locale

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("settings")
private val LANGUAGE_CODE = stringPreferencesKey("language_code")

class LanguageRepository(private val context: Context) {
    val availableLanguages = listOf(
        Language("zh-rCN", "简体中文", "🇨🇳"),
        Language("zh-rHK", "繁體中文(香港)", "🇭🇰"),
        Language("zh-rTW", "繁體中文(台灣)", "🇹🇼"),
        Language("en", "English", "🇺🇸"),
        Language("ja", "日本語", "🇯🇵")
    )

    val currentLanguageCode: Flow<String> = context.dataStore.data.map { preferences ->
        preferences[LANGUAGE_CODE] ?: getDefaultLocaleCode()
    }

    private fun getDefaultLocaleCode(): String {
        val locale = Locale.getDefault()
        return if (locale.country.isNullOrEmpty()) {
            locale.language
        } else {
            "${locale.language}_${locale.country}"
        }
    }

    suspend fun setLanguage(languageCode: String) {
        context.dataStore.edit { preferences ->
            preferences[LANGUAGE_CODE] = languageCode
        }
    }
}